package com.hs.telepass.ui;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnCheckedChanged;
import butterknife.OnClick;
import com.hs.teleform.R;
import com.hs.telepass.controller.TaskController;
import com.hs.telepass.controller.task.StartSingouSessionTask;
import com.hs.telepass.manager.PreferencesManager;
import com.hs.telepass.manager.SingouManager;
import com.hs.telepass.model.json.response.StartResponseItemJson;
import com.hs.telepass.ui.View.SwitchButton;
import com.hs.telepass.utils.LanguageUtil;
import com.hs.telepass.utils.RunTimeKeyUtil;

public class SettingFragment extends BaseFragment {

    @InjectView(R.id.switch_fast_login)
    SwitchButton mSwitchFastLogin;
    @InjectView(R.id.switch_sound)
    SwitchButton mSwitchSound;
    @InjectView(R.id.txtView_edit_password)
    TextView mTxtViewEditPassword;
    @InjectView(R.id.switch_login_need_password)
    SwitchButton mSwitchLoginNeedPassword;
    @InjectView(R.id.switch_notifition)
    SwitchButton mSwitchNotifition;
    @InjectView(R.id.txtview_chinese)
    TextView mTxtviewChinese;
    @InjectView(R.id.txtvie_english)
    TextView mTxtvieEnglish;
    @InjectView(R.id.layout_language)
    LinearLayout mLayoutLanguage;

    @OnCheckedChanged(R.id.switch_fast_login)
    void onFastLoginCheckd(boolean checked) {
        mPreferencesManager.setFastLoginSwitch(checked);
    }

    @OnCheckedChanged(R.id.switch_sound)
    void onSoundCheckd(boolean checked) {
        mPreferencesManager.setSoundSwitch(checked);
    }

    @OnCheckedChanged(R.id.switch_login_need_password)
    void onLoginNeedPasswordCheckd(boolean checked) {
        if (true == checked) {
            if (mPreferencesManager.getUserHasInitPsw()) {
                mPreferencesManager.setLoginPwdSwitch(checked);
            } else {
                Intent intent = new Intent(mContext, SingouPasswordActivity.class);
                intent.putExtra(SingouPasswordActivity.EXTRA_HAS_SINGOU_PASSWORD, false);
                intent.putExtra(SingouPasswordActivity.EXTRA_IS_FROM_NEED_PSW_SWITCH, true);
                startActivityForResult(intent, INTENT_RESULT_CHECKED);
            }
        } else {
            mPreferencesManager.setLoginPwdSwitch(checked);
        }
    }

    @OnCheckedChanged(R.id.switch_notifition)
    void onNotificationCheckd(boolean checked) {
        mPreferencesManager.setNotificationSwitch(checked);
    }

    @OnClick(R.id.txtView_edit_password)
    void onEditOnclick() {
        Intent intent = new Intent(mContext, SingouPasswordActivity.class);
        intent.putExtra(EXTRA_KEY_SID, mSid);
        intent.putExtra(EXTRA_KEY_RUNTIME_KEY, mRuntime_key);
        intent.putExtra(SingouPasswordActivity.EXTRA_HAS_SINGOU_PASSWORD, mPreferencesManager.getUserHasInitPsw());
        startActivity(intent);
    }

    @OnClick(R.id.layout_language)
    void onLanguageClick(){
        boolean isChinese = PreferencesManager.getInstance().isLanguageChinese();
        PreferencesManager.getInstance().setLanguageChinese(!isChinese);
        switchLanguage();
        LanguageUtil.setLanguage(context);


        Intent it = new Intent(getActivity(), MainActivity.class); //MainActivity是你想要重启的activity
        it.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        it.putExtra("initTabIndex", 2);
        getActivity().startActivity(it);
    }

    public static final String EXTRA_KEY_SID = "extra_key_sid";
    public static final String EXTRA_KEY_RUNTIME_KEY = "extra_key_runtime_key";
    public static final int INTENT_RESULT_CHECKED = 0;

    private Context mContext;
    private View mRootView;
    private PreferencesManager mPreferencesManager;

    private String mSid;
    private String mRuntime_key;
    private String mAccountId;
    private String mPassword;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        return inflateAndSetupView(inflater, container, savedInstanceState, R.layout.setting_fragment);
    }

    // 生成并设置根视图
    private View inflateAndSetupView(LayoutInflater inflater,
                                     ViewGroup container, Bundle savedInstanceState, int layoutResourceId) {
        mRootView = inflater.inflate(layoutResourceId, container, false);
        ButterKnife.inject(this, mRootView);
        return mRootView;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = getActivity();
        mPreferencesManager = PreferencesManager.getInstance();

        mRuntime_key = RunTimeKeyUtil.getUUIDByRules(RunTimeKeyUtil.getUUID());
        //保存起runtimekey
        SingouManager.getInstance().setRuntimeKey(mRuntime_key);

        mAccountId = PreferencesManager.getInstance().getAccountId();
        mPassword = PreferencesManager.getInstance().getPasswordKey();
        try {
            //主要为了获得accountId
            SingouManager.getInstance().startSingouSession(mAccountId, mPassword, mRuntime_key, true);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (INTENT_RESULT_CHECKED == requestCode && Activity.RESULT_OK == resultCode) {
            mPreferencesManager.setLoginPwdSwitch(true);
        } else {
            mSwitchLoginNeedPassword.setChecked(false);
        }
    }

    @Override
    public IntentFilter getIntentFilter() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(StartSingouSessionTask.ACTION_START_FOR_PASSWORD_TASK);
        return intentFilter;
    }

    @Override
    public void handleOnReceive(Intent intent) {
        String action = intent.getAction();
        if (StartSingouSessionTask.ACTION_START_FOR_PASSWORD_TASK.equals(action)) {
            handleStartSession(intent);
        }
    }

    private void handleStartSession(Intent intent) {
        int event = intent.getIntExtra(TaskController.EXTRA_EVENT,
                TaskController.EVENT_TASK_ERROR);
        switch (event) {
            case TaskController.EVENT_TASK_BEGIN:
                break;
            case TaskController.EVENT_TASK_END:

                break;
            case TaskController.EVENT_TASK_SUCCEED:
                StartResponseItemJson json = (StartResponseItemJson) intent.getSerializableExtra(TaskController.EXTRA_RESPONSE);
                mSid = json.getSid();
                //TODO start 统一 sid
                SingouManager.getInstance().setSid(mSid);
                PreferencesManager.getInstance().setAccountId(json.getAccountid());
                break;
            case TaskController.EVENT_TASK_FAILED:
                break;
            case TaskController.EVENT_TASK_ERROR:
                try {
                    SingouManager.getInstance().startSingouSession(mAccountId, mPassword, mRuntime_key, true);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                break;
            default:
                break;
        }

    }


    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initViews();
        //初始语言设置
        switchLanguage();
    }

    private void initViews() {
        mSwitchFastLogin.setChecked(mPreferencesManager.getFastLoginSwitch());
        mSwitchSound.setChecked(mPreferencesManager.getSoundSwitch());
        mSwitchLoginNeedPassword.setChecked(mPreferencesManager.getLoginPwdSwitch());
        mSwitchNotifition.setChecked(mPreferencesManager.getNotificationSwitch());
    }

    private void switchLanguage(){
        boolean isChinese = PreferencesManager.getInstance().isLanguageChinese();
        if(isChinese){
            mTxtviewChinese.setTextColor(getResources().getColor(R.color.white));
            mTxtviewChinese.setBackgroundResource(R.drawable.ch_press_textborder);
            mTxtvieEnglish.setTextColor(getResources().getColor(R.color.switch_blue));
            mTxtvieEnglish.setBackgroundResource(R.drawable.eng_normal_textborder);
        }else{
            mTxtvieEnglish.setTextColor(getResources().getColor(R.color.white));
            mTxtvieEnglish.setBackgroundResource(R.drawable.eng_press_textborder);
            mTxtviewChinese.setTextColor(getResources().getColor(R.color.switch_blue));
            mTxtviewChinese.setBackgroundResource(R.drawable.ch_normal_textborder);
        }
    }

}